home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5819 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  89 lines

  1. Path: tank.news.pipex.net!pipex!iol!usenet
  2. From: jab@iol.ie (J Alan Brogan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: I need help on putting 2 strings together into 1(concatenate)
  5. Date: Wed, 21 Feb 1996 15:17:59 GMT
  6. Organization: Ireland On-Line
  7. Message-ID: <4gfd3g$6oa@barnacle.iol.ie>
  8. References: <4gcr1b$ft3@cloner4.netcom.com>
  9. Reply-To: jab@iol.ie
  10. NNTP-Posting-Host: dialup-029.tralee.iol.ie
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13. spdcool@ix.netcom.com(SPD) wrote:
  14.  
  15. <SNIP>
  16. >struct data {
  17. >    char *full_name;
  18. >    int age;
  19. >    float salary;
  20. > };
  21.  
  22. >struct name  {
  23. >   char *first1, *last1;
  24. >  };
  25.  
  26.  
  27. >int main(void)
  28. >{ 
  29. >  struct name fname[3], lname[3];
  30. >  struct data secret[5];
  31. >  int i, ran;
  32.  
  33. >  fname[o].first1 = "Joe";
  34. >  fname[1].first1 = "Michael";
  35. >  fname[2].first1 = "Bruce";
  36. >  lname[0].last1 = "Jordan";
  37. >  lname[1].last1 = "Willis";
  38. >  lname[2].last1 = "Jackson";
  39.  
  40.  
  41. >  randomize()
  42. >  for (i = 0; i < 5; ++i)  {
  43. >   e = random(3);
  44. >   secret[i].full_name = fname[e].first1;/* the trouble some part begin
  45. >   e = random(3);
  46. >   strcat(secret[i].full_name," ");
  47. >   strcat(secret[i].full_name,lname[e].last1);  /*trouble ends here*/
  48.  
  49. <SNIP>
  50.  
  51. You haven't allocated any storage for secret[i].full_name. And
  52.      secret[i].full_name = fname[e].first1;
  53. makes it point at, eg "Joe", ie you are not copying "Joe" to your
  54. record, you are only making your record point to where "Joe" is alreay
  55. stored in memory.
  56.  
  57. The next two lines try to concatenate more characters on to
  58. secret[i].full_name, ie they try to copy chars into memory straight
  59. after where, eg "Joe" is stored. So what happens next is undefined, ie
  60. anything is possible. 
  61.  
  62. So your program might start overwriting the other names, or it might
  63. crash, or it might start printing the FAQ at you (if you're really
  64. lucky).
  65.  
  66. Try setting aside some memory that _you_ have control over (as opposed
  67. to memory the compiler sets aside for, eg, "Joe"), and if you want to
  68. assign a string, use strcpy(), not =.
  69.  
  70. For example :
  71.  
  72. # define        YOUR_SIZE    30
  73. struct data {
  74.     char full_name[YOUR_SIZE];
  75.     int age;
  76.     float salary;
  77.  };
  78.  
  79.   for (i = 0; i < 5; ++i)  {
  80.    e = random(3);
  81.    strcpy(secret[i].full_name,fname[e].first1);
  82.     /* etc */
  83.  }
  84.  
  85.  
  86. Bye from
  87. Alan @ Kerry, Ireland
  88.  
  89.